package com.ny.dao.lmpl;

import com.ny.dao.StudentDao;
import com.ny.entity.Student;
import com.ny.until.SqlConncetion;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDaolmpl  implements StudentDao {
    Connection connection = SqlConncetion.getConnection();

    public StudentDaolmpl() throws SQLException, ClassNotFoundException {
    }

    @Override
    public int add(Student student) throws SQLException {
        String sql = "insert into students(name,phone,password) values(?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, student.getStudentName());
        preparedStatement.setString(2, student.getStudentPhone());
        preparedStatement.setString(3, student.getStudentPassword());

        return preparedStatement.executeUpdate();

    }

    @Override
    public Student deleteStu(String username, String pwd) throws SQLException {
        String sql = "delete from students where name = ? and password = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, pwd);
        int i = preparedStatement.executeUpdate();
        if (i > 0) {
            return new Student();
        }
            return null;

    }

    @Override
    public Student login(String Studentname, String studentPassword) throws SQLException, ClassNotFoundException {
        String sql = "select * from students where name = ? and password = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, Studentname);
        preparedStatement.setString(2, studentPassword);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            Student student = new Student();
            student.setStudent_Id(resultSet.getInt("student_id"));
            student.setStudentName(resultSet.getString("name"));
            student.setStudentName(resultSet.getString("phone"));
            student.setStudentPassword(resultSet.getString("password"));
            return student;
        }
        return null;
    }
}


